package com.cskt.petproject178.task;

import com.cskt.petproject178.config.OrderDelayQueueConfig;
import com.cskt.petproject178.mapper.OrderMapper;
import com.cskt.petproject178.mapper.SkuMapper;
import com.cskt.petproject178.pojo.entity.Order;
import com.cskt.petproject178.pojo.exception.BaseException;
import com.cskt.petproject178.pojo.vo.OrderVO;
import com.cskt.petproject178.pojo.vo.StatusEnum;
import com.cskt.petproject178.util.Constant;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单超时处理任务
 *
 * @author 27013
 **/

@Component
public class OrderTask {
private static  final Logger log= LoggerFactory.getLogger(OrderTask.class);
@Resource
private OrderMapper orderMapper;
@Resource
private SkuMapper skuMapper;
    @RabbitListener(queues = OrderDelayQueueConfig.ORDER_DELAY_QUEUE_NAME)
    @Transactional //开启事务
    public void orderHandler(Message message){
        String orderNo = new String(message.getBody());
        log.info("从{}队列中获取到的超时订单号：{}",OrderDelayQueueConfig.ORDER_DELAY_QUEUE_NAME,orderNo);
        // todo 根据订单好对相应的订单及所管的sku做出响应的处理
        List<OrderVO> orderList = orderMapper.selectOrderVOByOrderNo(orderNo);
        //判断订单是否存在
        if (ObjectUtils.isEmpty(orderList)) {
            log.warn("当前订单不存在:orderNo{}",orderNo);
            throw new BaseException(StatusEnum.ORDER_NOT_EXIST);
        }
        //遍历订单列表
        for (OrderVO order : orderList) {
            //判断订单状态 必须是待支付 ，以及支付状态必须是未支付
            //只针对状态为待支付的订单做相应的处理
            if (!order.getOrderStatus().equals(Constant.OrderStatus.PENDING_PAYMENT) || !order.getPayStatus().equals(Constant.PayStatus.UNPAID)) {
                log.warn("当前订单状态异常，orderNo:{},orderStatus:{},payStatus:{}",orderNo,order.getOrderStatus(),order.getPayStatus());
                throw new BaseException(StatusEnum.ORDER_STATUS_ERROR);
            }
            //根据订单号修改订单状态和支付状态
            //以及回滚库存和销量
            orderMapper.updateOrderStatus(order.getOrderNo(),Constant.OrderStatus.TIMEOUT);
            skuMapper.updateSkuRollbackBySkuIdAndSkuNum(order.getSkuId(),order.getProductQuantity());
        }
    }
}
